package com.mod;

import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.locator.BaseLocator;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author jianxy
 * @date 2025-08-19 22:24
 */
@Service
public class ModbusService {
    @Autowired
    private ModbusMaster master;

    // 读取保持寄存器（功能码03）
    public Number readHoldingRegister(int slaveId, int offset) {
        try {
            BaseLocator<Number> locator = BaseLocator.holdingRegister(
                    slaveId, offset, DataType.TWO_BYTE_INT_SIGNED
            );
            return master.getValue(locator);
        } catch (Exception e) {
            throw new RuntimeException("读取寄存器失败", e);
        }
    }

    // 批量读取（优化性能）
    public short[] batchReadRegisters(int slaveId, int startOffset, int count) {
        try {
            ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(
                    slaveId, startOffset, count
            );
            ReadHoldingRegistersResponse response =
                    (ReadHoldingRegistersResponse) master.send(request);
            return response.getShortData(); // 返回原始寄存器值
        } catch (Exception e) {
            throw new RuntimeException("批量读取失败", e);
        }
    }
}
